#pragma once

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <unordered_map>
#include <string>
#include <sys/socket.h>
#include <unordered_map>

// 提供算法
#define SEQ ": "

static std::unordered_map<std::string, std::string> con_type_lib = {{"html", "text/html"},
                                                                    {"json", "application/json"},
                                                                    {"jpg", "image/jpeg"},
                                                                    {"png", "image/png"},
                                                                    {"js", "text/javascript"},
                                                                    {"css", "text/css"},
                                                                    {"map", "application/json"}};

static std::string Content_type_transform(const std::string &type)
{
    if (con_type_lib.find(type) != con_type_lib.end())
        return con_type_lib[type];
    return "application/ocstream";
    // return "suffix not find commit";
}

class Util
{
public:
    // 版本二：只读取一行，在外部进行行汇总。
    static int Readline(size_t _socket, std::string &out)
    {
        char ch;
        while (1)
        {
            int set = recv(_socket, &ch, 1, 0);
            if (set == -1)
            {
                FAIL("errno: %s", strerror(errno));
                return -1;
            }
            else if (set == 0)
            {
                WARN("%d cline close", _socket);
                return -1;
            }

            if (ch == '\r')
            {
                char s;
                // std::cout << "读取到反斜杠r" << std::endl;
                int tmp = recv(_socket, &s, 1, MSG_PEEK);
                if (tmp == -1)
                {
                    FAIL("errno: %s", strerror(errno));
                    return -1;
                }
                else if (tmp == 0)
                {
                    WARN("cline close");
                    return -1;
                }

                if (s == '\n')
                {
                    recv(_socket, &ch, 1, 0); // 将多余的\r给接收掉
                    break;
                }
                else  //普通元素添加上去
                {
                    out.push_back('\r');
                }
            }
            else if (ch == '\n')
            {
                recv(_socket, &ch, 1, 0); // 将多余的\n给接收掉
                break;
            }
            else
            {
                out.push_back(ch);
            }
        }
        // std::cout << "readline检测:" << out << std::endl;
        return 0;
    }

    // 首部分割开
    static int Stringcut(std::string &str, std::string &cut1,
                         std::string &cut2, const std::string &seq = SEQ)
    {
        cut1 = str.substr(0, str.find(seq));
        if (str.find(seq) == std::string::npos)
            return -1;
        cut2 = str.substr(str.find(seq) + seq.size());
        return 0;
    }
};
